import 'dart:async';
import 'dart:collection';
import 'package:dio/dio.dart';
import 'package:duo_zui/Util/config_color.dart';
import 'package:duo_zui/Util/screen_utils.dart';
import 'package:duo_zui/constant/cache_key.dart';
import 'package:duo_zui/constant/constant.dart';
import 'package:duo_zui/like_button/like_button.dart';
import 'package:duo_zui/model/model.dart';
import 'package:duo_zui/widget/BaseModuleWidget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:loading_animations/loading_animations.dart';
import 'package:share/share.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:webview_flutter/webview_flutter.dart';

import '../router.dart';
import 'Comments.dart';

class Choice {
  const Choice({this.choiceName, this.choiceValue});

  final String choiceName;
  final int choiceValue;
}

const List<Choice> choices = const <Choice>[
  const Choice(choiceName: Constant.popAgree, choiceValue: 0),
  const Choice(choiceName: Constant.popReport, choiceValue: 1),
  const Choice(choiceName: Constant.popCopy, choiceValue: 2),
  const Choice(choiceName: Constant.popReply, choiceValue: 3),
];

class DetailsPage extends StatefulWidget {
  Post article;
  String url;
  DetailsPage({Key key, this.article, this.url}) : super(key: key);

  @override
  _DetailsPageState createState() => _DetailsPageState();
}

class _DetailsPageState extends State<DetailsPage> {
  final Completer<WebViewController> _controller =
  Completer<WebViewController>();
  bool _isPageFinished = false;
  double _webViewHeight = 600;

  int _shortCommentsLength = 0;

  bool _isShowRetry = true;

  List<Comment> comments = [];

  String _comment = '';

  _initData() async {
    Dio dio = new Dio();
    String url = "http://www.appshuo.club/api/client/api/comments/all/${widget.article.id}?pageNum=1&pageSize=5";
    print(url);
    Response response = await dio.get(
        url);
    Reslut reslut = Reslut.fromJson(response.data);
    setState(() {
      comments.clear();
      comments.addAll(reslut.response.comments);
      _shortCommentsLength = comments.length;
    });
  }

  _addComment(params) async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    Dio dio = new Dio();
    String url = "http://www.appshuo.club/api/client/api/comment/add";
    Map<String, String> headers = new HashMap();
    headers['Content-Type'] = 'application/json';
    headers['accessToken'] = prefs.get(CacheKey.USE_NET_DATA);
    Options option = new Options(method: "post");
    option.headers = headers;
    Response response = await dio.request(url, data: params, options: option);
    Reslut reslut = Reslut.fromJson(response.data);
    _initData();
  }

  @override
  void initState() {
    super.initState();
    _initData();
  }

  // 顶部导航
  Widget _buildAppBar() {
    return transparentAppBar(
        context: context,
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back,
            color: ConfigColor.primaryText,
          ),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        actions: <Widget>[
          IconButton(
            icon: Icon(
              Icons.bookmark_border,
              color: ConfigColor.primaryText,
            ),
            onPressed: () {},
          ),
          IconButton(
            icon: Icon(
              Icons.share,
              color: ConfigColor.primaryText,
            ),
            onPressed: () {
              Share.share(widget.url.replaceAll('/appview', ''));
            },
          ),
        ]);
  }

  // 页标题
  Widget _buildPageTitle() {
    return Container(
      margin: EdgeInsets.all(10),
      child: Padding(
          padding: EdgeInsets.only(bottom: 10),
          child:Row(
            children: [
              CircleAvatar(
                radius: 20.0,
                backgroundImage: NetworkImage(widget.article.user.photo),
                backgroundColor: Colors.white,
              ),
              Padding(
                padding: const EdgeInsets.only(left: 10.0),
                child: Text(widget.article.user.nickname),
              ),
              Padding(
                padding: const EdgeInsets.only(left: 15.0),
                child: Text('阅读',style: TextStyle(color: Colors.black38,fontSize: 13.0)),
              ),
              Padding(
                padding: const EdgeInsets.only(left: 3.0),
                child: Text('${widget.article.readcount}',style: TextStyle(color: Colors.black38,fontSize: 13.0)),
              ),
              Expanded(
                child: GestureDetector(
                  child: Padding(
                    padding: EdgeInsets.only(left: ScreenUtils.screenW()/2-50,right: 10.0),
                    child: new SizedBox(
                      width: 50,
                      child: FlatButton(
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(0.0),
                            side: BorderSide(color: Colors.green)),
                        color: Colors.white,
                        textColor: Colors.green,
                        padding: EdgeInsets.all(8.0),
                        onPressed: () {},
                        child: Text(
                          "+ 关注",
                          style: TextStyle(
                            fontSize: 14.0,
                          ),
                        ),
                      ),
                    ),
                  ),
                  onTap: () {
                    MyRouter.pushNoParams(context,MyRouter.userPage);
                  },
                ),
              )
            ],
          )),
    );
  }

  // web内容
  Widget _buildWebView() {
    return Container(
      height: _webViewHeight,
      child: WebView(
        initialUrl:
        widget.url, //widget.url,
        javascriptMode: JavascriptMode.unrestricted,
        onWebViewCreated: (WebViewController webViewController) async {
          _controller.complete(webViewController);

          // String contentBase64 =
          //     base64Encode(const Utf8Encoder().convert(htmlPage));
          // await webViewController.loadUrl('data:text/html;base64,$contentBase64');
        },
        javascriptChannels: <JavascriptChannel>[
          _invokeJavascriptChannel(context),
        ].toSet(),
        navigationDelegate: (NavigationRequest request) {
          if (request.url != widget.url) {
            //toastInfo(msg: request.url);
            return NavigationDecision.prevent;
          }
          return NavigationDecision.navigate;
        },
        onPageStarted: (String url) {
          // Timer(Duration(seconds: 1), () {
          //   setState(() {
          //     _isPageFinished = true;
          //   });
          // _removeAd();
          // _getViewHeight();
          // });
        },
        onPageFinished: (String url) {
          _getWebViewHeight();
          setState(() {
            _isPageFinished = true;
          });
        },
        gestureNavigationEnabled: true,
      ),
    );
  }

  // 注册js回调
  JavascriptChannel _invokeJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'Invoke',
        onMessageReceived: (JavascriptMessage message) {
          print(message.message);
          var webHeight = double.parse(message.message);
          if (webHeight != null) {
            setState(() {
              _webViewHeight = webHeight;
            });
          }
        });
  }

  // 删除广告
  // _removeWebViewAd() async {
  //   await (await _controller.future)?.evaluateJavascript('''
  //       try {
  //         function removeElement(elementName){
  //           let _element = document.getElementById(elementName);
  //           if(!_element) {
  //             _element = document.querySelector(elementName);
  //           }
  //           if(!_element) {
  //             return;
  //           }
  //           let _parentElement = _element.parentNode;
  //           if(_parentElement){
  //               _parentElement.removeChild(_element);
  //           }
  //         }

  //         removeElement('module-engadget-deeplink-top-ad');
  //         removeElement('module-engadget-deeplink-streams');
  //         removeElement('footer');
  //       } catch{}
  //       ''');
  // }

  // 获取页面高度
  _getWebViewHeight() async {
    await (await _controller.future)?.evaluateJavascript('''
        try {
          // Invoke.postMessage([document.body.clientHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight]);
          let scrollHeight = document.documentElement.scrollHeight;
          if (scrollHeight) {
            Invoke.postMessage(scrollHeight);
          }
        } catch {}
        ''');
  }

  // 获取web浏览器像素密度
  // _getWebViewDevicePixelRatio() async {
  //   await (await _controller.future)?.evaluateJavascript('''
  //       try {
  //         Invoke.postMessage(window.devicePixelRatio);
  //       } catch {}
  //       ''');
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: _buildAppBar(),
        body: Stack(
          children: <Widget>[
            SingleChildScrollView(
              child: Column(
                children: <Widget>[
                  Divider(height: 1),
                  _buildPageTitle(),
                  Divider(height: 1),
                  _buildWebView(),
                  _buildList(context),
                ],
              ),
            ),
            _isPageFinished == true
                ? Container()
                : Align(
              alignment: Alignment.center,
              child: LoadingBouncingGrid.square(),
            ),
          ],
        ),
        bottomNavigationBar: BottomAppBar(
          child: talkFeild(),
        )
    );
  }

  Widget _buildList(BuildContext context) {
    var content;
    content = _buildItem(context);
    return content;
  }

  Widget _buildItem(BuildContext context) {
    Widget widget;
    if (comments.length != 0) {
      widget = _buildExpansionTileForShort();
    } else {
      widget = _buildTotal('$_shortCommentsLength 条短评论');
    }
    return widget;
  }

  Widget _buildExpansionTileForShort() {
    return new ExpansionTile(
      initiallyExpanded: true,
      title: new Text('$_shortCommentsLength 条短评论',
          style: new TextStyle(
              fontSize: 16.0,
              fontWeight: FontWeight.w500,
              color: Colors.black)),
      children: comments.map((model) {
        return _buildPopItem(model);
      }).toList(),
    );
  }

  Widget _buildPopItem(Comment item) {
    return new PopupMenuButton<Choice>(
        padding: EdgeInsets.zero,
        onSelected: (choice) {
          print(choice.choiceName);
        },
        child: _buildContentItem(item),
        itemBuilder: (BuildContext context) {
          return choices.map((Choice choice) {
            return new PopupMenuItem<Choice>(
              value: choice,
              child: new Text(choice.choiceName),
            );
          }).toList();
        });
  }

  Future<bool> onLikeButtonTapped(bool isLiked) async{
    /// send your request here
    // final bool success= await sendRequest();

    /// if failed, you can do nothing
    // return success? !isLiked:isLiked;

    return !isLiked;
  }

  Future<bool> onLikeButtonTap(bool isLiked, Post item) {
    ///send your request here
    final Completer<bool> completer = new Completer<bool>();
    _isLike(item.id,completer,item,isLiked);
    return completer.future;
  }

  _addLike(id,isLiked) async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    Dio dio = new Dio();
    String url = 'http://www.appshuo.club/api/client/api/article/applaud/${id}';
    Map<String, String> headers = new HashMap();
    headers['Content-Type'] = 'application/json';
    headers['accessToken'] = prefs.get(CacheKey.USE_NET_DATA);
    Options option;
    if(!isLiked){
      option = new Options(method: "post");
    }else{
      option = new Options(method: "delete");
    }
    option.headers = headers;
    Response response = await dio.request(url, data: {}, options: option);
    Reslut reslut = Reslut.fromJson(response.data);
  }

  _isLike (id,completer,item,isLiked) async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    if(prefs.getBool(CacheKey.USER_IS_LOGIN)?? false){
      _addLike(id, isLiked);
      Timer(const Duration(milliseconds: 200), () {
        item.likeFlag = !item.likeFlag;
        item.praiseCount =
        item.likeFlag ? item.praiseCount + 1 : item.praiseCount - 1;
        // if your request is failed,return null,
        completer.complete(item.likeFlag);
      });
    } else{
      Fluttertoast.showToast(msg: "请先登录");
    }
  }

  Widget _buildContentItem(Comment item) {
    return new InkWell(
      child: new Padding(
        padding: const EdgeInsets.only(left: 12.0, top: 12.0, right: 12.0),
        child: new Column(
          children: <Widget>[
            new Row(
              children: <Widget>[
                new CircleAvatar(
                  radius: 12.0,
                  backgroundImage: new NetworkImage(
                      item.user.photo == null ? Constant.defHeadimg : item.user.photo),
                ),
                new Padding(
                  padding: const EdgeInsets.only(left: 12.0, right: 12.0),
                  child: new Text('${item.user.nickname == null ? '无名氏' : item.user.nickname}',
                      style: new TextStyle(
                        fontSize: 16.0,
                        color: Colors.black,
                        fontWeight: FontWeight.w400,
                      )),
                ),
                new Expanded(
                    child: new Container(
                      child: new Align(
                        alignment: Alignment.topRight,
                        child: new Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: <Widget>[
                            new Icon(
                              Icons.thumb_up,
                              color: Colors.grey,
                              size: 18.0,
                            ),
                            new Text(
                              '(${item.applaudCount == null ? '0' : item.applaudCount})',
                              style: new TextStyle(color: Colors.grey),
                            )
                          ],
                        ),
                      ),
                    )),
              ],
            ),
            new Padding(
              padding:
              const EdgeInsets.only(left: 35.0, top: 4.0, bottom: 10.0),
              child: new Container(
                alignment: Alignment.topLeft,
                child: new Text('${item.content}',
                    style: new TextStyle(fontSize: 14.0, color: Colors.black)),
              ),
            ),
            CommentReferWidget(refers: item.children),
            new Padding(
              padding: const EdgeInsets.only(top: 12.0, bottom: 8.0),
              child: new Container(
                alignment: Alignment.topRight,
                child: new Text('${item.updateDate}'),
              ),
            ),
            new Divider(height: 1.0),
          ],
        ),
      ),
    );
  }

  Widget _buildReply(Comment item) {
    List<CommentChild> replyToModel = item.children;
    CommentChild child = replyToModel[0];
    if(replyToModel.length > 0){
        if (null != child) {
            return new Padding(
              padding: const EdgeInsets.only(left: 35.0, bottom: 12.0),
              child: new Container(
                alignment: Alignment.topLeft,
                child: new Text.rich(
                  new TextSpan(
                      text: '${child.user.nickname}：',
                      style: new TextStyle(
                          fontSize: 16.0,
                          color: Colors.black,
                          fontWeight: FontWeight.w400),
                      children: [
                        new TextSpan(
                            text: '${child.content}',
                            style: new TextStyle(
                              fontSize: 14.0,
                              color: Colors.grey[600],
                              fontWeight: FontWeight.w400,
                            ))
                      ]),
                ),
              ),
            );
          }
    } else {
      //不需要显示怎么办？
      return new Container(
        height: 0.0,
      );
    }
  }

  Widget _buildTotal(String content) {
    return new Column(
      children: <Widget>[
        new Padding(
          padding: const EdgeInsets.only(
              left: 8.0, top: 12.0, bottom: 12.0, right: 12.0),
          child: new Align(
            alignment: Alignment.centerLeft,
            child: new Text(
              content,
              style: new TextStyle(
                  fontSize: 16.0,
                  fontWeight: FontWeight.w500,
                  color: Colors.black),
            ),
          ),
        ),
        new Divider(height: 1.0),
      ],
    );
  }

  _islogin () async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    if(prefs.getBool(CacheKey.USER_IS_LOGIN)?? false){
      _addComment({"articleId":widget.article.id,"content":_comment,"replyUid":"","replyCommentId":"","parentId":0});
    } else{
      Fluttertoast.showToast(msg: "请先登录");
    }
  }

  //评论框
  Widget talkFeild(){
    return Row(
      children: <Widget>[
        Expanded(
          child: Container(
            margin: EdgeInsets.only(left: 20.0,top:5.0,bottom: 5.0),
            width: MediaQuery.of(context).size.width,
            alignment: AlignmentDirectional.center,
            height: 30.0,
            decoration: BoxDecoration(
                color: Color.fromARGB(255, 237, 236, 237),
                borderRadius: BorderRadius.circular(24.0)),
            child: TextField(
              // onSubmitted: onSubmitted,
              onTap: (){
                showModalBottomSheet(
                    isScrollControlled: true,
                    context: context,
                    builder: (BuildContext context){
                      return SingleChildScrollView(  // !important
                          child: Container(
                            padding: EdgeInsets.only(
                            bottom: MediaQuery.of(context).viewInsets.bottom),  // !important
                            child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                mainAxisSize: MainAxisSize.min,
                                children: <Widget>[
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    crossAxisAlignment: CrossAxisAlignment.end,
                                    children: <Widget>[
                                      Expanded(
                                        child: new TextField(
                                          onChanged: (str) {
                                            _comment = str;
                                            setState(() {});
                                          },
                                          decoration: InputDecoration(
                                            hintText: '期待您的评论...',
                                            border: null,
                                            focusedBorder: UnderlineInputBorder(
                                              borderSide: BorderSide(color: Colors.blue[300]),
                                            ),
                                          ),
                                          keyboardType: TextInputType.text,
                                          // maxLength: 250,
                                          // maxLines: 1,
                                          autofocus: true,
                                        ),
                                      ),
                                      IconButton(
                                        icon: Icon(Icons.send),
                                        onPressed: () {
                                          Fluttertoast.showToast(msg: "评论成功!");
                                          Navigator.pop(context);
                                          _islogin();
                                        },
                                      )
                                    ],
                                  ),
                                ],
                              ),
                      ));
                    }
                );
              },
              cursorColor: Color.fromARGB(255, 0, 189, 96),
              decoration: InputDecoration(
                contentPadding: const EdgeInsets.only(left: 10.0,bottom:12.0),
                border: InputBorder.none,
                hintText: '说两句儿...',
                hintStyle: TextStyle(
                    fontSize: 15, color: Color.fromARGB(255, 192, 191, 191)),
              ),
              style: TextStyle(fontSize: 15),
            ),
          ),
        ),
        GestureDetector(
          child: Padding(
            padding: EdgeInsets.only(left: 20.0),
            child: IconText(context, widget.article.commentCount == 0 ? '评论' : widget.article.commentCount, Constant.ASSETS_IMG +
                'ic_notification_tv_calendar_comments.png'),
          ),
          onTap: () {

          },
        ),
        Padding(
          padding: EdgeInsets.only(left: 20.0, right: 10),
          child: LikeButton(
              size: 20.0,
              likeCount: widget.article.praiseCount == 0 ? 0: widget.article.praiseCount,
              likeBuilder: (bool isLiked) {
                return Image.asset(Constant.ASSETS_IMG + 'ic_vote.png',fit: BoxFit.fitWidth,width: 25,height: 25,color: isLiked ? Colors.green : Colors.grey);
              },
              //key: _globalKey,
              countBuilder: (int count, bool isLiked, String text) {
                final ColorSwatch<int> color =
                isLiked ? Colors.pinkAccent : Colors.grey;
                Widget result;
                if (count == 0) {
                  result = Text(
                    '赞',
                    style: TextStyle(color: color),
                  );
                } else
                  result = Text(
                    count >= 1000
                        ? (count / 1000.0).toStringAsFixed(1) + 'k'
                        : text,
                    style: TextStyle(color: color),
                  );
                return result;
              },
              likeCountPadding: const EdgeInsets.only(left: 5.0),
              onTap: (bool isLiked)
              {
                return onLikeButtonTap(isLiked, widget.article);
              }
           )),
      ],
    );
  }

  TextStyle getStyle(Color color, double fontSize, {bool bold = false}) {
    return TextStyle(
        color: color,
        fontSize: fontSize,
        fontWeight: bold ? FontWeight.bold : FontWeight.normal);
  }

}

/// 透明背景 AppBar
Widget transparentAppBar({
  @required BuildContext context,
  Widget title,
  Widget leading,
  List<Widget> actions,
}) {
  return AppBar(
    backgroundColor: Colors.transparent,
    elevation: 0,
    title: title != null
        ? Center(
      child: title,
    )
        : null,
    leading: leading,
    actions: actions,
  );
}

/// 设置宽度
double duSetWidth(double width) {
  return ScreenUtil().setWidth(width);
}

/// 设置宽度
double duSetHeight(double height) {
  return ScreenUtil().setHeight(height);
}

/// 设置字体尺寸
double duSetFontSize(double fontSize) {
  return ScreenUtil().setSp(fontSize);
}
